<template>
	<view class="wrapper order order-safe-area">
		<view class="order-box order-addr">
			<view class="order-addr-tabs main-flex">
				<view class="order-addr-tabs-item main-flex-item" :class="mode === 1 ? 'active' : ''" @click="changeMode(1)">
					<text>配送到家</text>
					<view class="radian"></view>
				</view>
				<view class="order-addr-tabs-item main-flex-item" :class="mode === 2 ? 'active' : ''" @click="changeMode(2)" v-if="setStore?.indexMode === 1">
					<text>门店自提</text>
					<view class="radian"></view>
				</view>
				<view class="order-addr-tabs-item main-flex-item" v-else></view>
			</view>
			<view class="order-addr-box main-flex" @click="chooseAddress">
				<view class="order-addr-info main-flex-item" v-if="addressInfo">
					<view class="order-item main-flex-item main-flex">
						<uni-icons class="order-item-send" type="location" size="20" color="#333333"></uni-icons>
						<uni-tag
							v-if="addressInfo?.defaultFlag === 1"
							class="address-item-label"
							custom-style="
								margin-right: 10rpx;
								line-height: 24rpx;
								font-size: 20rpx;
								font-weight: 700;
								background-color: #e3230e;
								border-color: #e3230e;
								color: #fff;"
							text="默认"
							size="mini" ></uni-tag>
						<uni-tag
							v-if="addressInfo?.addrLabel"
							class="address-item-label"
							custom-style="
								margin-right: 10rpx;
								line-height: 24rpx;
								font-size: 20rpx;
								font-weight: 700;
								background-color: #FF9500;
								border-color: #FF9500;
								color: #fff;"
							:text="addressInfo?.addrLabel"
							size="mini" ></uni-tag>
						<text class="order-item-text1">{{addressInfo?.contacts}}</text>
						<text class="order-item-text1">{{addressInfo?.phone}}</text>
					</view>
					<view class="order-item main-flex">
						<text class="order-item-name">地址：{{addressInfo?.addr || ''}}{{addressInfo?.detail || ''}}</text>
					</view>
				</view>
				<view class="order-addr-null main-flex-item" v-else>
					<view class="order-item main-flex">
						<uni-icons class="order-item-send" type="location" size="20" color="#333333"></uni-icons>
						<text class="order-item-text1">请选择收货地址</text>
					</view>
				</view>
				<view class="order-addr-right">
					<uni-icons class="order-addr-right-icon" type="right" size="24" color="#333333"></uni-icons>
				</view>
			</view>
			<view class="order-addr-no" v-if="isPs">所选地址不在配送范围内</view>
		</view>
		
		<view class="order-box">
			<view class="goods-item main-flex" v-for="item in order.productList" :key="item.productId">
				<view class="goods-item-l">
					<image class="goods-item-pic" :src="imgUrl(item.productImg)" lazy-load></image>
				</view>
				<view class="goods-item-c main-flex-item main-flex">
					<view class="goods-item-name">{{item.productName}}</view>
					<view class="goods-item-other main-flex">
						<view class="goods-item-price">￥{{item.price}}</view>
						<view class="goods-item-count">
						{{item.number}} x {{item.productUnit}}
						</view>
					</view>
					<view class="goods-item-money">
						<text>总价：￥</text>
						<text class="goods-item-money-num">{{moneyStr(item.money)}}</text>
					</view>
					
				</view>
			</view>
			
			<view class="other-box">
				<view class="other-item main-flex">
					<view class="other-item-name">配送</view>
					<view class="other-item-text">快速配送</view>
				</view>
				<view class="other-item main-flex">
					<view class="other-item-name">积分</view>
					<view class="other-item-text">+{{total?.sendIntegral || 0 }}积分</view>
				</view>
				<view class="other-item main-flex" @click="goRemark">
					<view class="other-item-name">备注</view>
					<view class="other-item-text main-flex-item">{{order.remark || '填写备注'}}</view>
					<uni-icons class="order-addr-right-icon" type="right" size="16" color="#333333"></uni-icons>
				</view>
			</view>
		</view>
		
		<view class="order-box">
			<view class="money-item main-flex">
				<view class="money-item-name">商品总额</view>
				<view class="money-item-num">￥{{total?.originalPrice ? moneyStr(total?.originalPrice) : '0.00'}}</view>
			</view>
			<view class="money-item main-flex">
				<view class="money-item-name">运费</view>
				<view class="money-item-num">￥{{total?.freight ? moneyStr(total?.freight) : '0.00'}}</view>
			</view>
			<view class="money-item main-flex" @click="openConpon">
				<view class="money-item-name">优惠券</view>
				<view class="money-item-tip">已选{{useCouponCount}}张</view>
				<view class="money-item-num price">-￥{{total?.discountPrice ? moneyStr(total?.discountPrice) : '0.00'}}</view>
				<uni-icons type="right" size="16" color="#333333"></uni-icons>
			</view>
			<view class="money-item money-total main-flex">
				<view class="money-item-name">合计</view>
				<view class="money-item-num price">￥{{total?.actualPrice ? moneyStr(total?.actualPrice) : '0.00'}}</view>
			</view>
		</view>
		
		<view class="order-box">
			<view class="other-item main-flex" @click="openInvoice">
				<view class="other-item-name">发票</view>
				<view class="other-item-text" :class="`invoice${order.orderInvoice?.invoice || 0}`">{{arrText(invoiceList, order.orderInvoice?.invoice || 0)}}</view>
				<uni-icons class="order-addr-right-icon" type="right" size="16" color="#333333"></uni-icons>
			</view>
		</view>
		
		<view class="order-btns safe-area">
			<view class="order-btns-box main-flex">
				<view class="order-btns-money">
					<text>实付款</text>
					<text class="order-btns-money-unit">￥</text>
					<text class="order-btns-money-num">{{moneyStr(total.actualPrice)}}</text>
				</view>
				<button v-if="orderInfo?.id" :disabled="isPayOrder" :loading="isPayOrder" class="ty-button ty-button-confirm order-btns-btn" @click="payOrderFun">立即支付</button>
				<button v-else :disabled="isCreateOrder" :loading="isCreateOrder" class="ty-button ty-button-confirm order-btns-btn" @click="settlement">立即下单</button>
			</view>
		</view>
		
		<order-invoice
			:showInvoice="showInvoice"
			v-model="order.orderInvoice"
			@close="closeInvoice"></order-invoice>
		<choose-conpon
			:showConpon="showConpon"
			:total="total"
			:productList="order.productList"
			:couponList="order.couponList"
			:couponProductList="order.couponProductList"
			@confirm="confirmConpon"
			@close="closeConpon"></choose-conpon>
		<pay
			:showPay="showPay"
			:order="orderInfo"
			@success="successPay"
			@close="closePay"></pay>
		<!--价格变动-->
		<goods-change
			:showGoodsChange="showGoodsChange"
			:goodsList="goodsChangeList"
			@confirm="confirmGoodsChange"
			@close="closeGoodsChange"></goods-change>
	</view>
</template>

<script setup>
import { computed, ref, watch } from 'vue';
import { onReady, onLoad, onReachBottom, onShow, onHide, onUnload } from '@dcloudio/uni-app';
import useUserStore from '@/store/modules/user'
import useSetStore from '@/store/modules/set'
import useOrderStore from '@/store/modules/order'
import { throttle, debounce, sleep } from '@/uni_modules/uview-plus'
import {
	createOrder,
	orderDetail,
	orderCancel,
	orderExpress,
	orderConfirmReceipt,
	calculatProductList,
	orderCalculat } from "@/api/app_api/order"
import { Decimal } from 'decimal.js'
import modal from '@/plugins/modal'
import { invoiceList } from '@/utils/config'
import { arrText, serviceWeixin } from '@/utils/ty'
import { addressList } from "@/api/app_api/user"
import { twoType } from "@/api/app_api/category"

	const userStore = useUserStore()
	const setStore = useSetStore()
	const orderStore = useOrderStore()
	
	const id = ref('')
	const chooseGoods = ref([])
	onLoad((option) => {
		uni.$on('orderRemark', (e) => {
			order.value.remark = e?.remark || ''
		})
		uni.$on('chooseAddress', (e) => {
			getAddress()
		})
		getAddress()
		getMoney()
		if (userStore.isTc === 1) {
			getTwoType()
		}
	})
	onUnload(() => {
		uni.$off('orderRemark')
		uni.$off('chooseAddress')
	})
	const tcTypeList = ref([])
	const getTwoType = () => {
		twoType({
			id: userStore.tcCategoryId
		}).then(res => {
			tcTypeList.value = res.data || []
		})
	}
	
	const order = ref({
		remark: '',
		sellChannel: userStore.sellChannel,
		regionCode: userStore.regionCode,
		customerAddrId: '',
		couponList: [],
		couponProductList: [],
		orderInvoice: {
			invoice: 0,
			type: '',
			subject: '',
			accountAddr: '',
			company: '',
			companyAccount: '',
			companyAddr: '',
			companyCode: '',
			companyPhone: '',
			email: ''
		},
		productList: []
	})
	
	// 送货设置
	const mode = ref(userStore.mode)
	const changeMode = (type) => {
		mode.value = type
		if (userStore?.user?.customerType !== 1) {
			order.value.sellChannel = type === 2 ? 3 : 2
			getMoney()
		}
	}
	
	// 获取地址
	const addressArr = ref([])
	const addressId = ref('')
	const isPs = ref(false)
	const getAddress = () => {
		addressList().then(res => {
			addressArr.value = res.data
			addressId.value = uni.getStorageSync('addressId') || ''
			const addressFilter1 = addressArr.value.filter(item => item.id == addressId.value)
			const addressFilter2 = addressArr.value.filter(item => item.defaultFlag === 1)
			order.value.customerAddrId = addressFilter1?.[0]?.id || addressFilter2?.[0]?.id || ''
			if (addressFilter1?.[0]) {
				isPs.value = addressFilter1?.[0].regionCode != order.value.regionCode
			} else if (addressFilter2?.[0]) {
				isPs.value = addressFilter2?.[0].regionCode != order.value.regionCode
			}
		})
	}
	const addressInfo = computed(() => {
		const addressFilter1 = addressArr.value.filter(item => item.id == addressId.value)
		const addressFilter2 = addressArr.value.filter(item => item.defaultFlag === 1)
		return addressFilter1?.[0] || addressFilter2?.[0] || null
	})
	// 选择地址
	const chooseAddress = () => {
		if (orderInfo.value?.id) return false
		uni.navigateTo({
			url: '/pages/address/list?type=2'
		})
	}
	
	// 发票信息填写
	const showInvoice = ref(false)
	const openInvoice = () => {
		if (orderInfo.value?.id) return false
		showInvoice.value = true
	}
	const closeInvoice = () => {
		showInvoice.value = false
	}
	
	// 填写备注
	const goRemark = () => {
		if (orderInfo.value?.id) return false
		uni.navigateTo({
			url: order.value.remark?`/pages/order/remark?remark=${order.value.remark}`:`/pages/order/remark`
		})
	}
	
	// 优惠券选择
	const showConpon = ref(false)
	const openConpon = () => {
		if (orderInfo.value?.id) return false
		showConpon.value = true
	}
	const closeConpon = () => {
		showConpon.value = false
	}
	const confirmConpon = (e) => {
		order.value.couponList =  e.couponList
		order.value.couponProductList =  e.couponProductList
		orderCalculatFun()
	}
	
	// 计算价格
	const total = ref({})
	const getMoney = () => {
		const list = orderStore?.carOrder?.orderProductList || []
		const sellChannel = orderStore?.carOrder?.sellChannel || userStore.sellChannel
		return new Promise((resolve, reject) => {
		  calculatProductList(list, sellChannel).then(res => {
				if (res?.data) {
					total.value = res.data
					// order.value.customerAddrId = res.data?.customerAddrId || ''
					order.value.productList = res.data?.orderProductList.map(item => {
						const goodsFilter = list.filter(goods => goods.productId == item.productId)
						return {
							...item,
							typeId: goodsFilter?.[0]?.typeId || '',
							money: Decimal(item.price).mul(Decimal(item.number)).toNumber()
						}
					}) || []
					order.value.couponList =  res.data?.couponDetailList || []
					order.value.couponProductList =  res.data?.couponProductDetailList || []
					order.value.sellChannel = sellChannel
					resolve(res.data)
				} else {
					reject('信息错误')
				}
		  }).catch(err => {
				reject(err)
			})
		})
	}
	
	// 选择优惠券后计算
	const orderCalculatFun = () => {
		const list = order.value.productList
		orderCalculat({
			couponList: order.value.couponList,
			couponProductList: order.value.couponProductList,
			productList: list,
			sellChannel: order.value.sellChannel,
			customerAddrId: order.value.customerAddrId
		}).then(res => {
			total.value = res.data
			order.value.customerAddrId = res.data?.customerAddrId || ''
			order.value.productList = list.map(item => {
				const goodsFilter = list.filter(goods => goods.productId == item.productId)
				return {
					...item,
					typeId: goodsFilter?.[0]?.typeId || '',
					money: Decimal(item.price).mul(Decimal(item.number)).toNumber()
				}
			}) || []
			order.value.couponList =  res.data?.couponDetailList || []
			order.value.couponProductList =  res.data?.couponProductDetailList || []
		})
	}
	
	// 使用优惠券数量
	const useCouponCount = computed(() => {
		return order.value.couponList.length + order.value.couponProductList.length
	})
	
	// 价格变动
	const goodsChangeList = ref([])
	const showGoodsChange = ref(false)
	const settlement = async () => {
		if (order.value?.productList.length > 0) {
			const oldList = order.value.productList
			const newGoods = await getMoney()
			goodsChangeList.value = goodsChangeFun(oldList || [], newGoods?.orderProductList || [])
			if (goodsChangeList.value.length > 0) {
				showGoodsChange.value = true
			} else {
				createOrderFun()
			}
		} else {
			uni.$u.toast('结算商品不存在')
		}
	}
	const closeGoodsChange = () => {
		showGoodsChange.value = false
	}
	const confirmGoodsChange = () => {
		settlement()
		showGoodsChange.value = false
	}
	// 判断价格变动
	const goodsChangeFun = (oldList, newList) => {
		return oldList ? oldList.map(item => {
			const newFilter = newList.find(item1 => item1.productId === item.productId)
			return {
				oldGoods: item,
				newGoods: newFilter || null
			}
		}).filter(item => {
			return !item.newGoods || item.newGoods.price != item.oldGoods.price
		}) : []
	}
	
	// 立即下单
	const isCreateOrder = ref(false)
	const orderInfo = ref({})
	const createOrderFun = () => {
		if (orderInfo.value?.id) return false
		const params = {
			couponList: order.value.couponList,
			couponProductList: order.value.couponProductList,
			productList: order.value.productList,
			sellChannel: order.value.sellChannel,
			customerAddrId: order.value.customerAddrId,
			regionCode: order.value.regionCode,
			remark: order.value.remark
		}
		const addressFilter = addressArr.value.filter(item => item.id == params.customerAddrId && item.regionCode == params.regionCode)
		if (addressFilter.length === 0) {
			uni.$u.toast('该地址不在本单配送范围，请重新选择收货地址！')
			return false
		}
		if (order.value.orderInvoice.invoice === 1) {
			params.orderInvoice = {...order.value.orderInvoice}
			delete params.orderInvoice.invoice
		}
		const tcPrudoctFilter = params.productList.filter(item => tcTypeList.value.filter(type => type.id == item.typeId).length > 0)
		if (tcPrudoctFilter.length > 0) {
			uni.showModal({
				title: '下单提示',
				content: `订单中包含团餐商品，团餐商品下单后不提供退货服务，确认下单吗？`,
				success: function (res) {
					if (res.confirm) {
						createOrderParamsFun(params)
					} else if (res.cancel) {
					}
				}
			})
			return false
		}
		createOrderParamsFun(params)
	}
	const createOrderParamsFun = (params) => {
		isCreateOrder.value = true
		createOrder(params).then(res => {
			isCreateOrder.value = false
			if (res?.data) {
				orderInfo.value = res?.data
				showPay.value = true
			}
		}).catch(err => {
			isCreateOrder.value = false
		})
	}
	
	// 支付相关
	const isPayOrder = ref(false)
	const showPay = ref(false)
	const payOrderFun = () => {
		showPay.value = true
	}
	const closePay = () => {
		showPay.value = false
	}
	const successPay = (order) => {
		uni.redirectTo({
			url: `/pages/order/success?orderId=${order.orderId}&money=${order.actualPrice}&pId=${order.paymentId}&name=${order.payName}&orderNumber=${order.orderNumber}`
		})
	}
	
	
	watch(() => userStore.sellChannel, (nval, oval) => {
		if (nval) {
			order.value.sellChannel = nval
			getMoney()
		}
	})
	watch(() => userStore.regionCode, (nval, oval) => {
		if (nval) {
			order.value.regionCode = nval
		}
	})
</script>

<style lang="scss">
	.order {
		padding: 20rpx;
		&-box {
			border-radius: 20rpx;
			background-color: #ffffff;
			padding: 20rpx;
			&+.order-box {
				margin-top: 20rpx;
			}
		}
		&-item {
			font-size: 24rpx;
			&+.order-item {
				margin-top: 10rpx;
			}
			&-l {
				width: 280rpx;
			}
			&-name {
				color: $text-light;
			}
			&-send {
				margin-right: 10rpx;
			}
			&-text1 {
				font-size: 28rpx;
				margin-right: 20rpx;
			}
			&-icon {
				width: 32rpx;
				height: 32rpx;
				margin-left: 20rpx;
			}
		}
		&-addr {
			padding: 0;
			overflow: hidden;
			&-tabs {
				height: 80rpx;
				background-color: #dddddd;
				&-item {
					position: relative;
					font-size: 32rpx;
					text-align: center;
					line-height: 80rpx;
					border-radius: 20rpx 20rpx 0rpx 0rpx;
				}
				.active {
					background-color: #ffffff;
					&:before{
						content: '';
						position: absolute;
						width: 20rpx;
						height: 20rpx;
						bottom: 0;
						left: -20rpx;
						background: radial-gradient(circle at 0 0,
						      transparent 20rpx,
						      #ffffff 20rpx); 
					}
					&:after{
						content: '';
						position: absolute;
						width: 20rpx;
						height: 20rpx;
						bottom: 0;
						right: -20rpx;
						background: radial-gradient(circle at 20rpx 0,
						      transparent 20rpx,
						      #ffffff 20rpx); 
					}
				}
			}
			&-box {
				padding: 20rpx;
				background-color: #ffffff;
			}
			&-no {
				padding: 0rpx 20rpx 20rpx;
				font-size: 24rpx;
				color: $primary-color;
			}
		}
		.goods-item {
			align-items: flex-start;
			&+.goods-item {
				margin-top: 20rpx;
			}
			&-l {
				width: 160rpx;
				height: 160rpx;
				overflow: hidden;
				border-radius: 10rpx;
			}
			&-pic {
				width: 160rpx;
				height: 160rpx;
			}
			&-c {
				min-height: 160rpx;
				flex-direction: column;
				align-items: flex-start;
				justify-content: space-between;
				padding: 0 10rpx;
			}
			&-r {
				height: 160rpx;
				align-items: center;
				padding: 0 10rpx;
			}
			&-name {
				width: 100%;
				font-size: 26rpx;
				font-weight: 600;
				word-break: break-all;
			}
			&-other {
				width: 100%;
				margin-top: 4rpx;
			}
			&-count {
				font-size: 24rpx;
				color: $text-light;
				margin-left: auto;
			}
			&-price {
				font-size: 24rpx;
				color: $text-light;
			}
			&-money {
				width: 100%;
				font-size: 24rpx;
				text-align: right;
				color: $primary-color;
				&-num {
					font-size: 28rpx;
				}
			}
		}
		.money-item {
			&+.money-item {
				margin-top: 10rpx;
			}
			&-name {
				font-size: 26rpx;
			}
			&-num {
				font-size: 28rpx;
				color: #000000;
				font-weight: 600;
				margin-left: auto;
			}
			&-tip {
				padding: 0rpx 6rpx;
				font-size: 20rpx;
				border: 1px solid $primary-color;
				border-radius: 4rpx;
				margin-left: 20rpx;
				color: $primary-color;
			}
		}
		.money-total {
			padding: 30rpx 0 10rpx;
			margin-top: 0;
			border-top: 1px solid $line-color;
			.price {
				font-size: 32rpx;
			}
		}
		&-btns {
			position: fixed;
			width: 100%;
			left: 0;
			bottom: 0;
			background-color: #ffffff;
			box-sizing: border-box;
			&-box {
				width: 100%;
				padding: 20rpx;
				box-sizing: border-box;
			}
			&-money {
				font-size: 24rpx;
				&-unit {
					color: $price-color;
				}
				&-num {
					font-size: 32rpx;
					color: $price-color;
				}
			}
			&-btn {
				width: 180rpx;
				height: 60rpx;
				border-radius: 30rpx;
				font-size: 24rpx;
				margin-left: auto;
			}
		}
	}
	.order-safe-area {
		padding-bottom: calc(constant(safe-area-inset-bottom) + 108rpx); /* 兼容iOS <11.2 */
		padding-bottom: calc(env(safe-area-inset-bottom) + 108rpx); /* 兼容iOS ≥11.2 */
	}
	.other {
		&-box {
			margin-top: 40rpx;
		}
		&-item {
			align-items: flex-start;
			font-size: 24rpx;
			&+.other-item {
				margin-top: 20rpx;
			}
			&-name {
				padding-right: 20rpx;
			}
			&-text {
				margin-left: auto;
				text-align: right;
			}
		}
	}
	.invoice1 {
		color: $primary-color;
	}
</style>
